package com.honghu.cloud.interceptor;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.honghu.cloud.code.ResponseCode;
import com.honghu.cloud.constant.Globals;
import com.honghu.cloud.redis.RedisUtil;
import com.honghu.cloud.spring.SpringContextHolder;
import com.honghu.cloud.utils.JWT;

public class LoginPcInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		response.setCharacterEncoding("utf-8");
		// 从header中获取token
		String tokenStr = request.getHeader("token");
		// TODO token为空直接通过，后期需要确定那些服务登录后才能访问， 在这里拦截
		if(StringUtils.isEmpty(tokenStr)) { 
			// 后台管理token不能为空
			/*PrintWriter writer = response.getWriter();
			Map<String, Object> resultMap = ResponseCode.buildReturnMap(ResponseCode.TOKEN_NOTNULL, false);
        	responseMessage(response, writer, resultMap);
        	return false;*/
			return true;
		}
		
		// 解密token
		String token = JWT.unsign(tokenStr, String.class);
		
		// 验证token的合法性
		if(StringUtils.isEmpty(token) || token.indexOf(";") == -1){
			PrintWriter writer = response.getWriter();
			Map<String, Object> resultMap = ResponseCode.buildReturnMap(ResponseCode.ILLEGAL_TOKEN, false);
        	responseMessage(response, writer, resultMap);
        	return false;
		}
		
		// 从token获取用户id
		String [] tokens = token.split(";");
		Long userId = null2Long(tokens[0]);
		if(null == userId){
			PrintWriter writer = response.getWriter();
			Map<String, Object> resultMap = ResponseCode.buildReturnMap(ResponseCode.ILLEGAL_TOKEN, false);
        	responseMessage(response, writer, resultMap);
        	return false;
		}
		
		RedisUtil redisUtil = SpringContextHolder.getBean(RedisUtil.class);
		// 从redis中取出用户token
		String redisToken = (String) redisUtil.get(Globals.PC_LOGIN_MARK + userId);
		
		// redis中token为空  || redis中的token和header中的token不相等，提示：token已过期，请重新登录
		if(StringUtils.isEmpty(redisToken) || !StringUtils.equals(tokenStr, redisToken)){
			PrintWriter writer = response.getWriter();
			Map<String, Object> resultMap = ResponseCode.buildReturnMap(ResponseCode.TOKEN_EXPIRE, false);
        	responseMessage(response, writer, resultMap);
        	return false;
		}
		
		// 将用户id绑定到request中
		request.setAttribute("login_user_id", userId);
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	private void responseMessage(HttpServletResponse response, PrintWriter out, Object responseVO) {
		response.setContentType("application/json; charset=utf-8");  
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers",
                       "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");
        out.print(JSONObject.toJSON(responseVO).toString());
        out.flush();
        out.close();
    }
	
	public Long null2Long(String s) {
		Long v = null;
		if (s != null) {
			try {
				v = Long.parseLong(s);
			} catch (Exception localException) {
			}
		}
		return v;
	}

}
